import hashlib

from database.messsagDB import GroupInfo, MessageDB
from plugins.base_plugin import BasePlugin
from plugins.event_system import on_message, EventType, Event
import json
import os
import aiohttp
from common.logger import logger


class DifyAIPlugin(BasePlugin):
    def __init__(self, config, event_bus):
        super().__init__(config, event_bus)
        self.api_key = self.get_setting("api_key")
        self.api_url = self.get_setting("api_url")
        self.keywords = self.get_setting("keywords", [])
        self.max_tokens = self.get_setting("max_tokens", 1000)
        self.temperature = self.get_setting("temperature", 0.7)

    def should_respond(self, content,is_at: bool=False):
        if is_at:
            return True
        """判断是否应该响应消息"""
        # 如果消息以关键词开头，则响应
        for keyword in self.keywords:
            if content.startswith(keyword):
                return True
        return False

    def extract_query(self, content):
        """提取查询内容"""
        # 移除关键词前缀
        for keyword in self.keywords:
            if content.startswith(keyword):
                return content[len(keyword):].strip()
        return content

    async def call_dify_api(self, query, user_id,conversion_id:str):
        """调用Dify API"""
        try:
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            }

            payload = {
                "inputs": {},
                "query": query,
                "response_mode": "blocking",
                "user": user_id,
                "conversation_id": conversion_id,
                "auto_generate_name": True
            }

            url = f"{self.api_url}/chat-messages"

            async with aiohttp.ClientSession() as session:
                async with session.post(url, json=payload, headers=headers) as response:
                    if response.status == 200:
                        return await response.json()
                    else:
                        text = await response.text()
                        logger.error(f"Dify API调用失败: {response.status}, {text}")
                        return None

        except Exception as e:
            logger.error(f"Dify API调用异常: {e}")
            return None

    @on_message(EventType.MESSAGE_TEXT)
    async def handle_text_message(self, event:Event):
        """处理文本消息"""
        try:
            msg = event.data
            content = msg.content
            from_wxid = msg.from_wxid
            sender_wxid = msg.sender_wxid
            is_group=msg.is_group
            db = MessageDB()
            conversion_id= await db.get_convertion_id(from_wxid, sender_wxid,is_group,"dify:chat")
            # 检查是否应该响应
            if not self.should_respond(content,msg.is_at):
                return None

            # 提取查询内容
            query = self.extract_query(content)
            nickname=msg.sender_nickname if is_group else ''
            query=f'{nickname}:{query}'
            # 生成用户ID
            user_id = f"{from_wxid}"
            # 调用Dify API
            result = await self.call_dify_api(query, user_id,conversion_id)

            if result:
                answer = result.get("answer", "")
                await db.update_convertion_id(from_wxid, sender_wxid,is_group,result.get("conversation_id",""),"dify:chat")
                # 返回响应
                return self.create_text_response(answer)
            else:
                return self.create_text_response("抱歉，我暂时无法回答您的问题，请稍后再试。")
        except Exception as e:
            logger.error(f"处理文本消息异常: {e}")
            return None


# 创建插件实例
Plugin = DifyAIPlugin